/**
 * Created by yhg97p on 2016/9/27.
 */
define(['app', 'filters/filters'], function (app) {
    app.register.controller('trainCourse', function ($Ajax, $scope, $http, $state, $sce, $stateParams, $rootScope, $timeout) {
        var http = app._baseUrl;
        $scope.loading_show = true;
        $scope.curriculum_id = $stateParams.curriculum_id;
        $scope.show_tool = 0;
        $scope.show_course_period = false;
        $scope.judge = {
            isTeacherList: true,
            thisVideo: {},
            videoItem: [],
            firsetVideo: false,
            isfirstVideo: function () {
                this.firsetVideo = true;
            },
            isAjax: true,
            isPlay: false,
            showFirstImg: true,
            isPlayVideoNow: false
        };
        $scope.isAjaxing = true;
        $scope.isAjaxing_test = true;
        $scope.judge.isfirstVideo();
        //    练习弹窗
        $scope.questionModal = {
            isShow: false,
            title: '',
            data: {},
            confirm: function () {
                $scope.answering = true;
                $scope.finish = false;
                $http({
                    url: app._baseUrl + '/Qy/Task/questionList',
                    method: 'POST',
                    data: {
                        period_id: $rootScope.period_id,
                        task_type: 1
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).success(function (responed) {
                    $scope.questionList = responed.data;
                    $scope.questionlist = $scope.questionList.question_list;
                    for (i = 0; i < $scope.questionlist.length; i++) {
                        $scope.check_score = $scope.questionlist[i].check_score;
                        if ($scope.check_score == -1) {
                            questionindex = i;
                            break
                        }
                        if ($scope.check_score.indexOf(-1) == -1) {
                            questionindex = 0;
                        }
                    }
                    $rootScope.secondary = false;
                    $scope.listall = $scope.questionlist.length;
                    $scope.now_right_count = $scope.questionList.now_right_count;
                    $scope.now_wrong_count = $scope.questionList.now_wrong_count;
                    /*$scope.now_score = $scope.questionList.now_right_score;*/
                    $scope.paper_id = $scope.questionList.paper_id;
                    $rootScope.question = questionindex;
                    $scope.questionModal.title = "第" + parseInt($rootScope.question + 1) + "题";
                });
            },
            cancel: function () {
                this.hide();
            },
            video: function () {
                this.isVideo();
                //下一视频父index与上一视频父亲一样的
                $scope.parIndex = $scope.judge.thisVideo.itemIndex;
                //下一点击item
                $scope.nextItemSum = $scope.judge.videoItem[$scope.parIndex].period_list;
                //此时应该显示的下一视频项index
                $scope.thisvideoindex = parseInt($scope.judge.thisVideo.index1) + 1;
                //此时应该显示的下一视频项
                if ($scope.nextItemSum.length > $scope.thisvideoindex) {
                    $scope.nextItem = $scope.nextItemSum[$scope.thisvideoindex];
                } else if ($scope.judge.videoItem.length > $scope.parIndex + 1) {
                    $scope.parIndex = $scope.judge.thisVideo.itemIndex + 1;
                    $scope.nextItemSum = $scope.judge.videoItem[$scope.parIndex].period_list;
                    $scope.nextItem = $scope.nextItemSum[0];
                    $scope.thisvideoindex = 0;
                } else {
                    $scope.thisvideoindex = parseInt($scope.judge.thisVideo.index1);
                    $scope.nextItem = $scope.nextItemSum[$scope.thisvideoindex];
                }
                $scope.judge.isPlayVideoNow = true;
                $scope.play($scope.nextItem, $scope.thisvideoindex, $scope.parIndex);
                this.hide();
            },
            nowvideo: function () {
                this.hide();
                this.isVideo();
                $scope.play();
            },
            hide: function () {
                this.isShow = false;
            },
            show: function () {
                this.isShow = true;
            },
            isPauseVideo: false,
            isVideo: function () {
                this.isPauseVideo = true;
            }
        }
        /*-----------------初始化页面开始-----------------*/
        //课程概要、随堂练习、课程讲师
        $scope.tabList = [
            {
                title: '课程概要',
                value: 1
            },
            // {
            //     title: '随堂练习',
            //     value: 2
            // },
            {
                title: '课程讲师',
                value: 3
            }
        ];
        //tab默认选中
        $scope.tabIndex = $scope.tabList[0].value;
        $scope.changeTab = function (index) {
            $scope.tabIndex = index;
            if ($scope.tabIndex == 3) {
                $scope.getTeacherList();
            };
            if ($scope.tabIndex == 2 && $scope.isAjaxing_test == true) {
                $scope.isAjaxing_test = false;
                $scope.load_test.init && $scope.load_test.init();
            }
        }
        /*-----------------初始化页面结束------------------*/
        // $scope.API = null;
        // $scope.onPlayerReady = function(API) {
        //     $rootScope.API = API;
        // };
        $rootScope.states = 0;
        //----------------------------------加
        $scope.newPlay = {
            aliyun_video_id: '',
            VideoId: '',
            PlayAuth: '',
            player: {},
            req_aliyun_video_id: function (period_id) {//请求到aliyun_video_id；
                var url = http + 'Qy/Curriculum/periodInfo&period_id=' + period_id;
                $Ajax.get(url).then(function (res) {
                    if (res.data.success) {
                        $scope.newPlay.aliyun_video_id = res.data.data.aliyun_video_id;
                        $scope.newPlay.req_PlayAuth($scope.newPlay.aliyun_video_id);
                    }
                });
            },
            req_PlayAuth: function (aliyun_video_id) {//请求道PlayAuth视频播放凭证
                var url = http + '/Qy/Curriculum/getVideoPlayAuth&aliyun_video_id=' + aliyun_video_id;
                $Ajax.get(url).then(function (res) {
                    if (res.data.success) {
                        $scope.newPlay.VideoId = res.data.data.VideoMeta.VideoId;
                        $scope.newPlay.PlayAuth = res.data.data.PlayAuth;
                        $scope.newPlay.showVideo();
                    }
                })
            },
            showVideo: function (url) {
                if ($('#J_prismPlayer').text() != '') {
                    this.player.loadByUrl(url);
                } else {
                    this.player = new prismplayer({
                        id: "J_prismPlayer", // 容器id
                        width: "800px",
                        height: "450px",
                        autoplay: true,
                        source: url
                    })
                }
                // if ($('#J_prismPlayer').text() != '') {
                //     this.player.reloaduserPlayInfoAndVidRequestMts(this.VideoId, this.PlayAuth);
                // } else {
                //     var player = new prismplayer({
                //         id: "J_prismPlayer", // 容器id
                //         vid: this.VideoId,//媒体转码服务的媒体Id
                //         playauth: this.PlayAuth,
                //         width: "800px",
                //         height: "450px",
                //         autoplay: true,
                //         isLive: false,
                //         playsinline: true,
                //         controlBarVisibility: "always",
                //         showBuffer: false,
                //         useFlashPrism: true,
                //         useH5Prism: true,
                //         // useH5Prism:true,
                //         cover: ""
                //     });
                //     this.player = player;
                // }

            }
        };
        //----------------------------------加
        $scope.load = {
            _getPeriodInfoList: function () {
                $http({
                    url: app._baseUrl + 'Qy/Curriculum/lists&curriculum_id=' + $scope.curriculum_id,
                    method: 'GET',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (res) {
                    $scope.loading_show = false;
                    $scope.periodInfoList = res.data;
                    $scope.judge.videoItem = $scope.periodInfoList;//存储右侧视频列表
                    angular.forEach($scope.periodInfoList, function (v, k) {
                        v.index = k
                    });
                })
            },
            _getTrainCourseinfo: function () {  //专业类别和专业
                $http({
                    url: app._baseUrl + 'Qy/Curriculum/info&curriculum_id=' + $scope.curriculum_id,
                    method: 'GET',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (res) {
                    $scope.loading_show = false;
                    $scope.TrainCourseinfo = res.data;
                    $rootScope.secondary = false;
                });
            },
            init: function () {
                $scope.periodInfoList = $scope.periodInfo = [];
                this._getPeriodInfoList && this._getPeriodInfoList();
                if ($scope.tabIndex == 1 && $scope.isAjaxing == true) {
                    $scope.isAjaxing = false;
                    $scope.TrainCourseinfo = [];
                    this._getTrainCourseinfo && this._getTrainCourseinfo();
                }

            }
        };
        $scope.load.init && $scope.load.init();

        //滚轮
        $scope.help = {
            jqueryScrollbarOptions: {
                "onScroll": function (y, x) {

                }
            }
        };

        //        实验开始
        $scope.play = function (item, index1, parentIndex) {
            if ($scope.judge.firsetVideo == true) {
                $scope.questionModal.isPauseVideo = false;
                $scope.judge.firsetVideo = false;
            } else {
                $scope.questionModal.isPauseVideo = true;
            }
            if (item) {
                if (item.learned == -1) {

                    return false;
                } else {
                    $scope.period_id = item.period_id;
                }

            }
            $scope.chaper = function (index) {
                $scope.temp = index;
            };
            $scope.sectemp = index1;
            if ($scope.judge.isPlayVideoNow == false) {
                $rootScope.playing = false;
            } else {
                $rootScope.playing = true;
            }
            $scope.judge.showFirstImg = false;
            $http({
                url: app._baseUrl + 'Qy/Curriculum/periodInfo&period_id=' + $scope.period_id,
                method: 'GET',
                // dataType:'json',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).success(function (res) {
                // if(item){//有疑问？//待改
                //     if($scope.tabIndex == 2&&item.learned == 0){//当点击的是随堂练习并且视频锁状态是未学习状态，才发送请求随堂练习列表
                //         $scope.load_test.init && $scope.load_test.init();
                //     }
                // }
                // $rootScope.playing=true;
                // $scope.newPlay.req_aliyun_video_id($scope.period_id);

                $scope.newPlay.showVideo(item.video_url);
                $scope.load.init && $scope.load.init();

            });
        };
        //        实验结束
        //---------------------------------------------课程讲师信息
        $scope.getTeacherList = function () {
            if ($scope.judge.isTeacherList) {
                $scope.judge.isTeacherList = false;
                $http({
                    url: app._baseUrl + 'Qy/Curriculum/teacherList&curriculum_id=' + $scope.curriculum_id,
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).success(function (res) {
                    $scope.teacherList = res.data;
                });

            } else {
                return false;
            }

        };
        //---------------------------------------------课程讲师信息结束
        $scope.tipModal = {
            isShow: false,
            title: '温馨提示',
            data: {},
            confirm: function () {
                this.hide()
            },
            cancel: function () {
                this.hide()
            },
            hide: function () {
                this.isShow = false;
            },
            show: function () {
                this.isShow = true;
            }
        };
        if ($rootScope.num == 0) {
            $scope.tipModal.show();
            $rootScope.num = 1;
        }

        //当前页面处于浏览器选中状态
        var hiddenProperty = 'hidden' in document ? 'hidden' :
            'webkitHidden' in document ? 'webkitHidden' :
                'mozHidden' in document ? 'mozHidden' :
                    null;
        var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
        var onVisibilityChange = function () {
            if (!document[hiddenProperty]) {
                //location.reload();
                $http({
                    url: app._baseUrl + 'Qy/Curriculum/chapterPeriodList&curriculum_id=' + $scope.curriculum_id,
                    method: 'GET',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (res) {
                    $scope.Curriculuminfo = res.data;
                    angular.forEach($scope.Curriculuminfo, function (v, k) {
                        v.index = k

                    });
                    $rootScope.secondary = false;
                });

            }
        };
        document.addEventListener(visibilityChangeEvent, onVisibilityChange);

        $scope.load_test = {
            _getTrainCourseinfo: function () {  //课程信息
                $http({
                    url: app._baseUrl + 'Qy/Curriculum/info&curriculum_id=' + $scope.curriculum_id,
                    method: 'GET',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (res) {
                    $scope.loading_show = false;
                    $scope.TrainCourseinfo = res.data;
                    $rootScope.secondary = false;
                    $scope.teacher_list = $scope.TrainCourseinfo.teacherList;
                    $scope.len = $scope.teacher_list.length;
                    $rootScope.imgLen = $scope.len;
                    $(".teaBox").css('width', $scope.len * 240)//ul宽度


                });

            },
            _getCurriculuminfo: function () {  //课程列表
                $http({
                    url: app._baseUrl + 'Qy/Curriculum/chapterPeriodList&curriculum_id=' + $scope.curriculum_id,
                    method: 'GET',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (res) {
                    $scope.loading_show = false;
                    $scope.Curriculuminfo = res.data;
                    angular.forEach($scope.Curriculuminfo, function (v, k) {
                        v.index = k

                    });
                    $rootScope.secondary = false;


                });

            },
            init: function () {
                // $scope.TrainCourseinfo = [];
                $scope.Curriculuminfo = [];
                // this._getTrainCourseinfo && this._getTrainCourseinfo();
                this._getCurriculuminfo && this._getCurriculuminfo();
            }
        };

        $rootScope.bstop = true;//不明白干嘛的，猜测是是否发送Ajax请求吧
        //    给随堂练习-开始练习一个点击事件
        $scope.questionPop = function (item, parentIndex, index1) {
            $scope.ti_index = 0;
            $scope.answering = true;
            $scope.finish = false;
            $scope.period_id = item.period_id;
            $scope.judge.thisVideo = {
                itemIndex: parentIndex || 0,
                index1: index1 || 0
            };
            $rootScope.period_id = item.period_id;
            //获取题目列表
            $http({
                url: app._baseUrl + '/Qy/Task/questionList',
                method: 'POST',
                data: {
                    period_id: $rootScope.period_id,
                    // task_type:$scope.ques_type
                    task_type: 1
                },
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (responed) {
                if (responed.success) {
                    //console.log(responed.data)
                    $scope.questionModal.show();
                    $scope.questionList = responed.data;
                    $scope.questionlist = $scope.questionList.question_list;
                    for (i = 0; i < $scope.questionlist.length; i++) {//未作答就从1开始作答
                        $scope.check_score = $scope.questionlist[i].check_score;
                        if ($scope.check_score == -1) {
                            questionindex = i;
                            break
                        }
                        if ($scope.check_score.indexOf(-1) == -1) {
                            questionindex = 0;
                        }
                    }
                    $rootScope.secondary = false;
                    $rootScope.listall = $scope.questionlist.length;
                    $scope.now_right_count = $scope.questionList.now_right_count;
                    $scope.now_wrong_count = $scope.questionList.now_wrong_count;
                    /* $scope.now_score = $scope.questionList.now_right_score;*/
                    $scope.paper_id = $scope.questionList.paper_id;
                    //区分单选还是多选再去累计题目
                    $rootScope.question = questionindex;
                    $scope.questionModal.title = "第" + parseInt($rootScope.question + 1) + "题";

                } else {
                    $scope.sec = 5;
                    var interval = setInterval(function () {//设置定时器
                        if ($scope.sec > 0) {
                            $scope.sec--;
                            $scope.tipShow = true;//提示显示
                            $scope.tipmess = '该课时还没有随堂任务';//将提示信息绑定
                            $('.black_patch').fadeIn(600);
                        } else {
                            clearInterval(interval);
                            $scope.tipShow = true;
                            $('.black_patch').fadeOut(600);
                        }
                        $scope.$digest();//脏数据检验
                    }, 500)
                }
            });

            $scope.answer = function (k, item) {
                if ($rootScope.bstop == true) {
                    $http({
                        url: app._baseUrl + '/Qy/Task/answerCheck',
                        method: 'POST',
                        data: {
                            paper_id: $scope.paper_id,
                            question_id: item.question_id,
                            s_answer: k
                        },
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        }
                    }).success(function (responed) {
                        $rootScope.bstop = false;
                        $scope.answerList = responed.data;
                        $rootScope.secondary = false;
                        $scope.numb = 0;
                        $scope.check_score = $scope.answerList.check_score;
                        $scope.questionList.now_right_score = responed.data.total_score;
                        $scope.now_star_num = responed.data.star_num;
                        if ($scope.check_score > 0) {//正确
                            $scope.questionList.now_right_count += 1;
                            $scope.score = parseInt($scope.check_score);
                            /*  $scope.questionList.now_right_score += $scope.score;*/
                        } else if ($scope.check_score == 0) {//错误
                            $scope.questionList.now_wrong_count += 1;
                        }
                        var gitanswer = function () {
                            $rootScope.question += 1;
                            $scope.questionModal.title = "第" + parseInt($rootScope.question + 1) + "题";
                            if ($rootScope.question == $rootScope.listall) {
                                $scope.answering = false;
                                $scope.finish = true;
                                $scope.load.init && $scope.load.init();//更新视频列表
                                $scope.load_test.init && $scope.load_test.init();
                                $scope.questionModal.title = "";
                            }
                            $scope.numb = 1;
                            $rootScope.bstop = true;

                        };
                        $timeout(gitanswer, 1000);
                    }
                    );
                    return false
                }
            }

        };

        //图片放大
        $scope.img_big = false;
        $scope.img_click = function (img) {
            $scope.img_big = !$scope.img_big;
            $scope.scaleImg = img;
            var imgObj = new Image();
            imgObj.src = img; //若是jq，则直接将此代码换成 imgObj.src = _test.attr("src"); 即可。
            var k = document.body.clientWidth / 2 - imgObj.width / 2;
            var v = document.body.clientHeight / 2 - imgObj.height / 2;
            $(".bigImgBox").css("left", k + 'px');
            $(".bigImgBox").css("top", v + 'px');
            $scope.obj_img = {
                left: k,
                top: v,
                width: imgObj.width,
                height: imgObj.height
            }
            $(".bigImgBox").css("left", $scope.obj_img.left + 'px');
            $(".bigImgBox").css("top", $scope.obj_img.top + 'px');
            $('.bigImgBox .bigImg').css({ 'width': $scope.obj_img.width, "height": $scope.obj_img.height });
        }
        //图片放大结束
        var divImg = document.getElementsByClassName('bigImgBox');
        divImg[0].addEventListener("DOMMouseScroll", function (e) {
            var imgWidth = $('.bigImgBox .bigImg').width();
            var imgHeight = $('.bigImgBox .bigImg').height();
            var imgLeft = divImg[0].offsetLeft;
            var imgTop = divImg[0].offsetTop;
            //console.log(e)
            if (e.detail > 0) {
                imgLeft = imgLeft - imgWidth / 20;
                imgTop = imgTop - imgHeight / 20;
                imgWidth = imgWidth + imgWidth / 10;
                imgHeight = imgHeight + imgHeight / 10;
                $('.bigImgBox').css({ 'left': imgLeft, 'top': imgTop })
                $('.bigImgBox .bigImg').css({ 'width': imgWidth, "height": imgHeight });
            }
            if (e.detail < 0) {
                imgLeft = imgLeft + imgWidth / 20;
                imgTop = imgTop + imgHeight / 20;
                imgWidth = imgWidth - imgWidth / 10;
                imgHeight = imgHeight - imgHeight / 10;
                $('.bigImgBox').css({ 'left': imgLeft, 'top': imgTop })
                $('.bigImgBox .bigImg').css({ 'width': imgWidth, "height": imgHeight });
            }
        });

        divImg[0].addEventListener('mousewheel', function (e) {
            var imgWidth = $('.bigImgBox .bigImg').width();
            var imgHeight = $('.bigImgBox .bigImg').height();
            var imgLeft = divImg[0].offsetLeft;
            var imgTop = divImg[0].offsetTop;
            if (e.deltaY > 0 || e.wheelDelta < 0) {
                imgLeft = imgLeft - imgWidth / 20;
                imgTop = imgTop - imgHeight / 20;
                imgWidth = imgWidth + imgWidth / 10;
                imgHeight = imgHeight + imgHeight / 10;
                $('.bigImgBox').css({ 'left': imgLeft, 'top': imgTop })
                $('.bigImgBox .bigImg').css({ 'width': imgWidth, "height": imgHeight });
            }
            if (e.deltaY < 0 || e.wheelDelta > 0) {
                imgLeft = imgLeft + imgWidth / 20;
                imgTop = imgTop + imgHeight / 20;
                imgWidth = imgWidth - imgWidth / 10;
                imgHeight = imgHeight - imgHeight / 10;
                $('.bigImgBox').css({ 'left': imgLeft, 'top': imgTop })
                $('.bigImgBox .bigImg').css({ 'width': imgWidth, "height": imgHeight });
            }
        });

    })
})